import { Module } from 'vuex';
import {RootStateTypes} from '../index';
import { getToken, setToken } from '@/utils/auth';
import { login } from '@/api/user';

interface userMouduleTypes {
    token: string,
    name: string,
    roles: string[],
    permissions: string[]
}

const user: Module<userMouduleTypes, RootStateTypes> = {
  state: {
    token: getToken(),
    name: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token: string): void => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    }
  },

  actions: {
    // 登录
    async Login({ commit }, userInfo) {
      const username = userInfo.username;
      const password = userInfo.password;
      const res = await login({ username, password });
      if (res.data && res.data.token) {
        const token = res.data.token;
        setToken(token);
        commit('SET_TOKEN', token);
      }
      return res;
    }
  }
};

export default user;
